package com.ten.course.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ten.common.core.entity.TbPlayHistory;
import com.ten.common.core.vo.Result;
import com.ten.course.dao.PlayHistoryDao;
import com.ten.course.service.PlayHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author ：张成（3092211427@qq.com）
 * @date ：Created in 2022/12/28 13:50
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class PlayHistoryServiceImpl implements PlayHistoryService {

    @Autowired
    private PlayHistoryDao playHistoryDao;

    /**
     * 根据会员id分页查询会员观看课程的历史记录
     * @param currentPage 当前页码
     * @param pageSize 当前页面显示条数
     * @param memberId 会员id
     * @return Result<Page<TbPlayHistory>>
     */
    @Override
    public Result<Page<TbPlayHistory>> queryPlayHistoryBy(Integer currentPage, Integer pageSize, String memberId) {
        Page<TbPlayHistory> page = new Page<>(currentPage, pageSize);
        Page<TbPlayHistory> page1 = playHistoryDao.queryPlayHistoryBy(page, memberId);
        return new Result<>(200, "查询成功", page1);
    }

    /**当用户访问课程时，对于观看课程的历史记录进行添加
     * @param courseId  课程id
     * @param huiYuanId 会员id
     * @param videoId   视频id
     *       在初次观看的时候，进行添加，后来观看更新记录
     * @return
     */
    @Override
    public Result insertPlayHistoryByCourseId(String courseId, String huiYuanId, String videoId) {
        //1.判断该记录是否存在，如果存在，则更新观看历史时间
        QueryWrapper<TbPlayHistory> wrapper =new QueryWrapper<>();
        wrapper.eq("user_id",huiYuanId);
        wrapper.eq("vedeo_id",videoId);
        TbPlayHistory playHistory = playHistoryDao.selectOne(wrapper);
        System.out.println(playHistory);
        if(playHistory!=null){
            playHistory.setPlayTimePoint(LocalDateTime.now());
            int update = playHistoryDao.updateById(playHistory);
            if(update>0){
                return new Result(200,"修改课程观看记录成功");
            }
            return new Result(500,"修改课程观看记录失败");
        }
        TbPlayHistory tbPlayHistory =new TbPlayHistory();
        //2.如果不存在该项历史记录，则进行添加操作
        String id = IdUtil.getSnowflakeNextId() + "";
        tbPlayHistory.setPlayId(id);
        tbPlayHistory.setUserId(huiYuanId);
        tbPlayHistory.setVedeoId(videoId);
        int insert = playHistoryDao.insert(tbPlayHistory);
        if(insert>0){
            return new Result(200,"添加课程观看记录成功");
        }
        return new Result(500,"添加课程观看记录失败");
    }
}